<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>课程列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 搜索筛选 -->
        <el-form :inline="true" class="user-search">
            <el-form-item>
                <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
            </el-form-item>
        </el-form>

        <!--列表-->
        <el-table size="small" :data="listData" highlight-current-row v-loading="loading" border
            element-loading-text="拼命加载中" style="width: 100%;">

            <el-table-column align="center" type="index" label="序号" width="60">
            </el-table-column>

            <el-table-column prop="name" label="课程名称" width="300">
            </el-table-column>

            <el-table-column prop="image" label="课程封面" width="300">
                <template slot-scope="scope">
                    <img :src="scope.row.image" style="height: 68px;width: 68px;border-radius: 6px" />
                </template>
            </el-table-column>
            <el-table-column prop="price" label="价格" width="300">
            </el-table-column>
            <el-table-column prop="classType" label="班型" width="300">
            </el-table-column>
            <el-table-column prop="give" label="赠送" width="300">
            </el-table-column>

            <el-table-column prop="target" label="招生对象" width="300">

            </el-table-column>

            <el-table-column prop="sort" label="课程排序(值越小越靠前)" width="300">
            </el-table-column>

            <el-table-column align="center" label="操作" min-width="300" fixed="right">
                <template slot-scope="scope">
                    <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="deleteCategory(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 编辑界面 -->
        <el-dialog :title="title" :visible.sync="editFormVisible" width="60%" @click='closeDialog("edit")'>
            <el-form label-width="200px">
                <el-form-item label="课程名称" prop="name">
                    <el-input size="small" v-model="param.name" auto-complete="off" placeholder="请输入课程名称"></el-input>
                </el-form-item>

                <el-form-item label="首页分类类别">
                    <el-select @change="selectCourseIdChange" :multiple="false" v-model="param.courseId"
                        placeholder="请选择首页分类类别" style="width:240px;">
                        <el-option v-for="item in courseList" :key="item.name" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="课程二级分类类别">
                    <el-select :multiple="false" v-model="param.categoryId" placeholder="请选择课程二级分类类别"
                        style="width:240px;">
                        <el-option v-for="item in courseListThree" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="课程价格">
                    <el-input size="small" v-model="param.price" auto-complete="off" placeholder="请输入课程价格"></el-input>
                </el-form-item>
                <el-form-item label="学习目标">
                    <el-input size="small" v-model="param.pri" auto-complete="off" placeholder="请输入学习目标"></el-input>
                </el-form-item>
                <el-form-item label="课程班型">
                    <el-input size="small" v-model="param.classType" auto-complete="off"
                        placeholder="请输入课程班型"></el-input>
                </el-form-item>
                <el-form-item label="课程课时">
                    <el-input size="small" v-model="param.time" auto-complete="off" placeholder="请输入课程课时"></el-input>
                </el-form-item>
                <el-form-item label="课程赠送" prop="give">
                    <el-input size="small" v-model="param.give" auto-complete="off" placeholder="请输入课程赠送"></el-input>
                </el-form-item>
                <el-form-item label="课程封面" style="">
                    <div class="upload-demo" style="display: flex;align-items: center;">
                        <el-upload action="" :http-request="mainImgUpload" :show-file-list="false"
                            list-type="picture-card">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                        <div style="position:relative;margin-left: 24px;" v-if="param.image">
                            <img :src="param.image" class="avatar" />

                            <div class="deleUrl">
                                <el-button type="danger" icon="el-icon-delete" circle @click="delImageClick()">
                                </el-button>
                            </div>
                        </div>

                    </div>
                </el-form-item>
                <el-form-item label="招生对象" prop="target">
                    <el-input size="small" v-model="param.target" auto-complete="off" placeholder="请输入招生对象"></el-input>
                </el-form-item>
                <el-form-item label="班号" prop="classNos">
                    <el-input size="small" v-model="param.classNos" auto-complete="off" placeholder="请输入班号"></el-input>
                </el-form-item>
                <el-form-item label="上课时间">
                    <el-date-picker v-model="classTimeArr" align="center" type="daterange" range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="上课校区">
                    <el-select multiple v-model="outlets_ids" placeholder="请选择校区" style="width:240px;">
                        <el-option v-for="item in outLetsLst" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="课程分类排序(值越小越靠前)" prop="sort">
                    <el-input size="small" v-model="param.sort" auto-complete="off" placeholder="请输入排序"></el-input>
                </el-form-item>
                <el-form-item label="课程详情" style="height: 500px;">
                    <quill-editor v-model="param.text" :options="editorOption" style="height: 400px;" ref="QuillEditor">
                    </quill-editor>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click='closeDialog("edit")'>取消</el-button>
                <el-button size="small" type="primary" :loading="loading" class="title" @click="addCategory()"
                    v-if="title == '添加'">添加</el-button>
                <el-button size="small" type="primary" :loading="loading" class="title" @click="upCategory()"
                    v-if="title == '修改'">修改</el-button>
            </div>
        </el-dialog>

        <el-dialog title="选择图片" :visible.sync="uploadVisible" width="30%">
            <div>
                <div class="upload-demo">
                    <el-upload action="" :http-request="mainImgRichUpload" :show-file-list="false"
                        list-type="picture-card">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <!-- <img v-if="formData.mainImg" :src="formData.mainImg" class="avatar"> -->

                </div>
            </div>
        </el-dialog>
    </div>
</template>
<script>

import {
    addCourseDetails, selectCourseByCategoryTypes, selectCourseDetails, selectOutletsAlls, updateCourseDetails, deleteCourseDetailByIds
} from "../../api/userMG";
import client from "@/utils/ossClient.js";

import Pagination from "../../components/Pagination";
import VueQuillEditor from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
// 工具栏配置
const toolbarOptions = [
    ["bold", "italic", "underline", "strike"], // toggled buttons
    ["blockquote", "code-block"],

    [{ header: 1 }, { header: 2 }], // custom button values
    [{ list: "ordered" }, { list: "bullet" }],
    [{ script: "sub" }, { script: "super" }], // superscript/subscript
    [{ indent: "-1" }, { indent: "+1" }], // outdent/indent
    [{ direction: "rtl" }], // text direction

    [{ size: ["small", false, "large", "huge"] }], // custom dropdown
    [{ header: [1, 2, 3, 4, 5, 6, false] }],

    [{ color: [] }, { background: [] }], // dropdown with defaults from theme
    [{ font: [] }],
    [{ align: [] }],
    ["link", "image", "video"], // 对于图片上传这是重点
    ["clean"], // remove formatting button
];
export default {
    data() {
        return {
            loading: false, //是显示加载
            editFormVisible: false, //控制编辑页面显示与隐藏
            menuAccessshow: false, //控制数据权限显示与隐藏
            title: "添加",
            name: "",
            courseList: [],
            courseListTwo: [],
            courseListThree: [],
            // 删除
            seletedata: {
                ids: "",
                token: localStorage.getItem("logintoken"),
            },
            listData: [], //用户数据

            // 分页参数
            pageparm: {
                currentPage: 1,
                pageSize: 10,
                total: 10,
            },
            uploadVisible: false,
            param: {
                name: '雅思课程一班',//课程名称
                classTime: '',
                image: 'http://yytc-img.oss-cn-qingdao.aliyuncs.com/1712737111185.jpeg',
                classType: '10人',
                target: '招生对象介绍',
                give: '送老婆',
                price: '213',//价格
                sort: '1221',
                pri: '',
                classNos: '',//班号                outletsIds: "",
                categoryId: '',//课程详情分类id
                courseId: '',//课程id
                time: '',
            },
            outlets_ids: [],
            outLetsLst: [],
            classTimeArr: [],
            editorOption: {
                modules: {
                    toolbar: {
                        container: toolbarOptions, // 工具栏
                        handlers: {
                            image: (value) => {
                                if (value) {
                                    // 在这里编写图片按钮点击操作
                                    this.uploadVisible = true;
                                    this.cursorIndex =
                                        this.$refs.QuillEditor.quill.getSelection().index;
                                } else {
                                    this.quill.format("image", false);
                                }
                            },
                        },
                    },
                },
            },
        };
    },
    // 注册组件
    components: {
        Pagination,
    },
    /**
     * 数据发生改变
     */
    watch: {},
    computed: {
        // typeName() {
        //     return typeId => {
        //         let name = ''
        //         this.courseList.forEach(item => {
        //             if (item.id == typeId) {
        //                 name = item.name

        //             }
        //         })
        //         return name
        //     }
        // },
        typeTwoName() {
            return typeId => {
                let name = ''
                this.courseListTwo.forEach(item => {
                    if (item.id == typeId) {
                        name = item.name

                    }
                })
                return name
            }
        }
    },
    /**
     * 创建完毕
     */
    created() {
        this.getdata()
        this.getCourseTypeLst()
        this.getCourseTypeTwoLst()
        this.outLetsLstFn()
    },
    /**
     * 里面的方法只有被调用才会执行
     */

    methods: {
        mainImgRichUpload(file) {
            //判断扩展名
            let self = this
            const tmpcnt = file.file.name.lastIndexOf(".");
            const exname = file.file.name.substring(tmpcnt + 1);
            const names = ["jpg", "jpeg", "webp", "png", "bmp"];
            if (names.indexOf(exname) < 0) {
                this.$message.error("不支持的格式!");
                return;
            }
            const fileName = file.file.uid + "." + exname;
            client
                .put(fileName, file.file)
                .then((res) => {
                    if (res.url) {
                        self.getUrl(res.url);
                    } else {
                        this.$message.error("文件上传失败");
                    }
                })
                .catch((err) => { });
        },
        getUrl(url) {
            this.uploadVisible = false;
            // 获取富文本组件实例
            let quill = this.$refs.QuillEditor.quill;
            // 如果上传成功
            if (url) {
                // 插入图片，res为服务器返回的图片链接地址

                quill.insertEmbed(this.cursorIndex, "image", url);
                // 调整光标到最后
                quill.setSelection(this.cursorIndex + 1);
            } else {
                // 提示上传失败信息
            }
        },
        delImageClick() {
            this.param.image = ''
        },
        mainImgUpload(file) {
            //判断扩展名
            const tmpcnt = file.file.name.lastIndexOf(".");
            const exname = file.file.name.substring(tmpcnt + 1);
            const names = ["jpg", "jpeg", "webp", "png", "bmp"];
            if (names.indexOf(exname) < 0) {
                this.$message.error("不支持的格式!");
                return;
            }
            const fileName = file.file.uid + "." + exname;
            client
                .put(fileName, file.file)
                .then((res) => {
                    if (res.url) {
                        this.param.image = res.url;
                    } else {
                        this.$message.error("文件上传失败");
                    }
                })
                .catch((err) => { });
        },
        outLetsLstFn() {
            selectOutletsAlls().then((res) => {
                if (res.code == 200) {
                    this.outLetsLst = res.data.data;
                    return;
                }
            });
        },
        //前往课程详情
        addCourseDetail(item) {
            localStorage.setItem('courseItem', item)
            this.$router.push({ path: '/course/courseDetail' });
        },
        // 添加分类
        addCategory() {
            if (!this.param.categoryId) {
                return this.$message.error('首页分类类别不能为空')
            }
            if (!this.param.categoryId) {
                return this.$message.error('课程二级分类类别不能为空')
            }
            if (this.classTimeArr.length > 0) {
                let classTimeOne = this.classTimeArr[0].getTime() / 1000
                let classTimeTwo = this.classTimeArr[1].getTime() / 1000
                this.param.classTime = `${classTimeOne},${classTimeTwo}`
            } else {
                return this.$message.error('上课时间未选择');
            }

            if (this.outlets_ids.length > 0) {
                this.param.outletsIds = this.outlets_ids.join(',')
            } else {
                return this.$message.error('上课校区未选择');
            }

            console.log('addCategory', this.param)

            this.loading = true;

            addCourseDetails({
                ...this.param
            }).then((res) => {
                this.loading = false;
                if (res.code == 200) {
                    this.editFormVisible = false
                    this.$message({
                        type: "success",
                        message: res.msg,
                    });
                    this.getdata();
                } else {
                    this.$message.error(res.msg);
                }
            });
        },
        // 修改
        upCategory() {
            if (this.classTimeArr.length > 0) {
                let classTimeOne = this.classTimeArr[0].getTime() / 1000
                let classTimeTwo = this.classTimeArr[1].getTime() / 1000
                this.param.classTime = `${classTimeOne},${classTimeTwo}`
            } else {
                return this.$message.error('上课时间未选择');
            }

            if (this.outlets_ids.length > 0) {
                this.param.outletsIds = this.outlets_ids.join(',')
            } else {
                return this.$message.error('上课校区未选择');
            }
            console.log('this.param=====', this.param)

            this.loading = true;
            updateCourseDetails({
                ...this.param
            }).then((res) => {
                this.loading = false;
                if (res.code == 200) {
                    this.editFormVisible = false
                    this.$message({
                        type: "success",
                        message: res.msg,
                    });
                    this.getdata();
                } else {
                    this.$message.error(res.msg);
                }
            });
        },
        getCourseTypeLst() {
            selectCourseByCategoryTypes({
                categoryType: 0,
            }).then((res) => {
                this.loading = false;
                if (res.code == 200) {
                    this.courseList = res.data.data;
                    return;
                }
                this.$message({
                    type: "info",
                    message: res.msg,
                });
            });
        },
        getCourseTypeTwoLst() {
            selectCourseByCategoryTypes({
                categoryType: 1,
            }).then((res) => {
                this.loading = false;
                if (res.code == 200) {
                    this.courseListTwo = res.data.data;
                    return;
                }
                this.$message({
                    type: "info",
                    message: res.msg,
                });
            });
        },
        selectCourseIdChange(e) {
            this.courseListThree = []
            this.param.categoryId = ''

            let arr = this.courseListTwo.filter(item => {
                return item.courseId == e
            })
            this.courseListThree = arr

        },
        selectCourseIdTwoChange(e, categoryId) {
            this.courseListThree = []


            let arr = this.courseListTwo.filter(item => {
                return item.courseId == e
            })
            this.courseListThree = arr
            console.log('arr===', arr)
            console.log('categoryId===', categoryId)
            this.param.categoryId = categoryId;

        },
        // 获取数据方法
        getdata() {
            this.loading = true;
            selectCourseDetails().then((res) => {
                this.loading = false;
                if (res.code == 200) {
                    this.listData = res.data.data;

                    return;
                }
                this.$message({
                    type: "info",
                    message: res.msg,
                });
            });
        },
        // 分页插件事件
        callFather(parm) {
            this.formInline.page = parm.currentPage;
            this.formInline.limit = parm.pageSize;
            this.getdata(parm.currentPage);
        },

        //显示编辑界面
        handleEdit: function (row) {
            this.editFormVisible = true;
            if (row != undefined && row != "undefined") {
                console.log('==handleEdit==', row)
                this.title = "修改";
                this.param.id = row.id;
                this.param.name = row.name;
                this.classTimeArr = row.classTime.split(',')
                let time = this.classTimeArr[0]
                let time2 = this.classTimeArr[1]

                this.classTimeArr[0] = new Date(time * 1000)
                this.classTimeArr[1] = new Date(time2 * 1000)
                this.param.image = row.image;
                this.param.classType = row.classType;
                this.param.target = row.target;
                let outLetsArr = row.outletsIds.split(',');
                this.outlets_ids = []
                if (outLetsArr.length > 0) {
                    outLetsArr.forEach(item => {
                        this.outLetsLst.forEach(outLetsItem => {
                            console.log('outLetsItem', outLetsItem)
                            if (item == outLetsItem.id) {
                                this.outlets_ids.push(
                                    Number(outLetsItem.id)
                                )
                            }
                        })
                    })
                    console.log('this.outlets_ids', this.outlets_ids)
                }

                this.param.give = row.give;
                this.param.price = row.price;
                this.param.pri = row.pri;
                this.param.classNos = row.classNos;
                this.param.courseId = row.courseId;
                this.selectCourseIdTwoChange(row.courseId, row.categoryId)
                this.param.sort = row.sort;
                this.param.time = row.time;

            } else {
                this.title = "添加";
                this.classTimeArr = []
                this.param.name = "";
                this.param.classTime = "";
                this.param.image = "";
                this.param.classType = "";
                this.param.target = "";
                this.param.give = "";
                this.param.price = "";
                this.param.pri = "";
                this.param.classNos = "";
                this.param.categoryId = "";
                this.param.courseId = "";
                this.param.sort = "";
                this.param.time = "";

            }
        },

        // 删除
        deleteCategory(index, row) {
            this.$confirm("确定要删除吗?", "信息", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    deleteCourseDetailByIds({ id: row.id })
                        .then((res) => {
                            if (res.code == 200) {
                                this.$message({
                                    type: "success",
                                    message: "已删除！",
                                });
                                this.getdata();
                            } else {
                                this.$message({
                                    type: "info",
                                    message: res.msg,
                                });
                            }
                        })
                        .catch((err) => {
                            this.loading = false;
                            this.$message.error("删除失败，请稍后再试！");
                        });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除",
                    });
                });
        },

        // 关闭编辑、增加弹出框
        closeDialog(dialog) {
            if (dialog == "edit") {
                this.editFormVisible = false;
            } else if (dialog == "perm") {
                this.menuAccessshow = false;
            }
        },
    },
};
</script>

<style scoped>
.user-search {
    margin-top: 20px;
}

.userRole {
    width: 100%;
}
</style>